package com.xinchao.ck_mips.presenter;

import android.media.AudioManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.orhanobut.logger.Logger;
import com.xinchao.ck_mips.App;
import com.xinchao.ck_mips.BuildConfig;
import com.xinchao.ck_mips.base.CKSubscriber;
import com.xinchao.ck_mips.base.MyBasePresenter;
import com.xinchao.ck_mips.bean.ConfigBean;
import com.xinchao.ck_mips.bean.DeviceInfoBean;
import com.xinchao.ck_mips.bean.NewestProgramBean;
import com.xinchao.ck_mips.bean.OffLineData;
import com.xinchao.ck_mips.bean.ProgramBean;
import com.xinchao.ck_mips.bean.ProgramInfoBean;
import com.xinchao.ck_mips.bean.SourceInfoBean;
import com.xinchao.ck_mips.bean.UpgradeBean;
import com.xinchao.ck_mips.constant.CK;
import com.xinchao.ck_mips.dao.DaoUtil;
import com.xinchao.ck_mips.event.DownloadCompleteEvent;
import com.xinchao.ck_mips.filedownload.SingleDownload;
import com.xinchao.ck_mips.impl.PlayModelImpl;
import com.xinchao.ck_mips.logic.PlayLogic;
import com.xinchao.ck_mips.model.IDownCallbackListener;
import com.xinchao.ck_mips.model.IPlayModel;
import com.xinchao.ck_mips.utils.DeviceUtil;
import com.xinchao.ck_mips.utils.FileUtils;
import com.xinchao.ck_mips.utils.NetWorkUtil;
import com.xinchao.ck_mips.utils.ShareUtil;
import com.xinchao.ck_mips.view.IPlayView;
import com.xinchao.devicemanage.DeviceManager;
import com.xinchao.devicemanage.util.MD5Util;
import com.xinchao.devicemanage.util.SharedPreferencesUtil;

import org.json.JSONArray;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import de.greenrobot.event.EventBus;
import io.reactivex.Flowable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by wq on 2019/5/6.
 */
public class PlayPresenter extends MyBasePresenter<IPlayView> {
    IPlayModel mIPlayModel = new PlayModelImpl();
    private boolean isConfigSuccess;
    private static final int REPORT_TIME = 10;
    private List<DeviceInfoBean.PollConfig> mPollBean;
    private long pollCount;
    private String currentDownVersion;
    private String deviceOpenClose = "";
    private List<SourceInfoBean> mList = new ArrayList<>();
    private List<SourceInfoBean> downList = new ArrayList<>();
    private String programVersion = "";
    private String updateVersion = "";
    private String settingVersion = "";
    private String key = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

    private IPlayModel getIPlayModel() {
        if (null == mIPlayModel) {
            mIPlayModel = new PlayModelImpl();
        }

        return mIPlayModel;
    }

    /**
     * 终端轮询
     */
    public void report(int time, boolean isFirst) {
        Flowable.timer(time, TimeUnit.SECONDS, Schedulers.io()).subscribe(new CKSubscriber<Long>(null) {
            @Override
            protected void next(Long aLong) {
                getIPlayModel().report(DeviceUtil.getWorkingHours(),
                        getView().getIP(), DeviceUtil.getBootTime(), new IPlayModel.IReportCallbackListener() {
                            @Override
                            public void success(DeviceInfoBean bean) {
                                //解析json数据
                                if (bean != null) {
                                    if (bean.getPollConfig() != null) {
                                        mPollBean = bean.getPollConfig();
                                    }

                                    if (isFirst) {
                                        //首次请求，轮询
                                        startPoll();
                                        init();
                                        isConfigSuccess = true;
                                    }

                                    if (!TextUtils.isEmpty(bean.getToken())) {
                                        //权限token非空时,替换本地token
                                        ShareUtil.getInstance().putToken(bean.getToken());
                                    }
                                    if (bean.getNewChange() != null) {
                                        if (bean.getNewChange().getNewProgram() != null) {
                                            //有新节目，获取最新节目信息
                                            if (TextUtils.isEmpty(programVersion) || !programVersion.equals("" + bean.getNewChange().getNewProgramUpdateTime())) {
                                                programVersion = "" + bean.getNewChange().getNewProgramUpdateTime();
                                                getNewestProgram("" + bean.getNewChange().getNewProgramUpdateTime());
                                            }
                                        }

                                        if (bean.getNewChange().getNewSetting() != null) {
                                            //有新设置信息，同步服务器
                                            if (TextUtils.isEmpty(settingVersion) || !settingVersion.equals("" + bean.getNewChange().getNewSettingUpdateTime())) {
                                                settingVersion = "" + bean.getNewChange().getNewSettingUpdateTime();
                                                getNewestSetting("" + bean.getNewChange().getNewSettingUpdateTime());
                                            }
                                        }

                                        if (bean.getNewChange().getNewUpgrade() != null) {
                                            //有升级信息，获取最新信息
                                            if (TextUtils.isEmpty(updateVersion) || !updateVersion.equals("" + bean.getNewChange().getNewUpgradeUpdateTime())) {
                                                updateVersion = "" + bean.getNewChange().getNewUpgradeUpdateTime();
                                                getNewestUpgrade("" + bean.getNewChange().getNewUpgradeUpdateTime());
                                            }
                                        }
                                    }
                                }
                            }

                            @Override
                            public void error(Throwable t) {
                                Logger.t(CK.TAG).e("report--requestError:" + t.getMessage());
                                if (!TextUtils.isEmpty(t.getMessage())) {
                                    if (!TextUtils.isEmpty(t.getMessage())) {
                                        if (t.getMessage().contains("-100")) {
                                            //非法设备，先绑定
                                            getView().finishAct();
                                            return;
                                        } else if (t.getMessage().contains("-102")) {
                                            //注册
                                            getView().finishAct();
                                            return;
                                        } else if (t.getMessage().contains("-103")) {
                                            getView().finishAct();
                                            return;
                                        }
                                    }
                                }

                                if (!isConfigSuccess) {
                                    //获取初始配置，直到成功
                                    report(REPORT_TIME, isFirst);
                                }
                            }
                        });
            }
        });
    }

    private void init() {
        //上传日志
        //获取最新节目
        //同步设置
        // upLoadWifiProbes();
    }

    /**
     * 轮询接口，周期执行
     */
    private void startPoll() {
        Flowable.timer(1, TimeUnit.SECONDS, Schedulers.io()).subscribe(new CKSubscriber<Long>(getView().getDisposable()) {
            @Override
            protected void next(Long aLong) {
                pollCount++;
                if (mPollBean != null) {
                    for (DeviceInfoBean.PollConfig pollBean : mPollBean) {
                        //到指定轮询时间后，请求接口
                        if (pollCount % pollBean.getPollIntervalTime() == 0) {
                            switch (pollBean.getPollName()) {
                                case "REPORT":
                                    report(0, false);
                                    break;
                                case "NEW_SETTING":
                                    settingVersion = "";
                                    getNewestSetting("");
                                    break;
                                case "NEW_UPGRADE":
                                    updateVersion = "";
                                    getNewestUpgrade("");
                                    break;
                                case "NEW_PROGRAM":
                                    programVersion = "";
                                    getNewestProgram("");
                                    break;
                            }
                        }
                    }
                }
            }

            @Override
            protected void finish() {
                startPoll();
            }
        });
    }

    /**
     * 获取最新升级信息
     */
    public void getNewestUpgrade(String serialNo) {
        if (!NetWorkUtil.isNetworkAvailable(getView().getContext())) {
            return;
        }
        getIPlayModel().getUpgrade(new IPlayModel.IUpgradeCallbackListener() {
            @Override
            public void success(List<UpgradeBean> list) {
                //获取升级信息后，反馈
                getUpgradeReply(serialNo);
                if (list != null && list.size() > 0) {
                    for (int i = 0; i < list.size(); i++) {
                        if (list.get(i).getUpgradeType().intValue() == 0) {
                            //apk升级
                            updateAPK(list.get(i));
                        }
                    }
                }
            }

            @Override
            public void error(Throwable t) {
                Logger.e(t.getMessage());
            }
        });
    }

    /**
     * 升级apk信息
     *
     * @param bean
     */
    private void updateAPK(UpgradeBean bean) {
        if (bean.getVersionCode() <= BuildConfig.VERSION_CODE) {
            return;
        }
        if (bean.getIsTiming() != null) {
            File apkFile = new File(FileUtils.getAPKFilePath(bean.getVersionCode().intValue()));
            if (!apkFile.exists()) {
                //不存在就下载
                downAPK(bean);
            } else if (!MD5Util.getFileMD5String(apkFile).equals(bean.getMd5())) {
                //md5值不一致,删除文件，重新下载
                apkFile.delete();
                downAPK(bean);
            } else {
                if (bean.getIsTiming().intValue() == 1) {
                    //定时升级
                    upgradeAPK(bean);
                } else {
                    //马上升级安装apk
                    DeviceUtil.installApp(apkFile.getAbsolutePath(), getView().getContext());
                }
            }
        }
    }

    /**
     * 下载apk文件
     *
     * @param bean
     */
    private void downAPK(UpgradeBean bean) {
        //下载apk
        SingleDownload.getInstance().downSingleFile(bean.getUrl(), FileUtils.getAPKFilePath(bean.getVersionCode().intValue()), new IDownCallbackListener() {
            @Override
            public void completed(String tag) {
                Message msg = Message.obtain();
                msg.what = 4;
                msg.obj = bean;
                mHandler.sendMessage(msg);
            }

            @Override
            public void error(String url, Throwable t) {
            }

            @Override
            public void progressed() {

            }

            @Override
            public void pending() {

            }
        });
    }

    /**
     * 获取终端升级信息后，反馈给服务端
     */
    public void getUpgradeReply(String serNo) {
        if (!NetWorkUtil.isNetworkAvailable(getView().getContext())) {
            return;
        }
        getIPlayModel().getUpgradeReply(serNo, new IPlayModel.IUpgradeReplyCallbackListener() {
            @Override
            public void success() {

            }

            @Override
            public void error(Throwable t) {
                Logger.e(t.getMessage());
                getUpgradeReply(serNo);
            }
        });
    }

    /**
     * 获取最新节目信息
     */
    public void getNewestProgram(String serialNo) {
        if (!NetWorkUtil.isNetworkAvailable(getView().getContext())) {
            return;
        }
        getIPlayModel().getNewestProgram(DeviceUtil.getResidualCapacity(), new IPlayModel.IProgramCallbackListener() {
            @Override
            public void success(NewestProgramBean bean) {
                getNewestProgramReply(serialNo, bean);
            }

            @Override
            public void error(Throwable t) {

            }
        });
    }

    /**
     * 保存节目素材信息
     *
     * @param bean
     */
    private void saveProgramData(NewestProgramBean bean) {
        try {
            Log.v("xika", "program:" + new Gson().toJson(bean));
            if (bean.getNewProgram().size() == 0) { 
                //删除本地数据库过期的节目数据
                PlayLogic.getInstance().deleteDBProgram(bean);
                //更新节目列表
                EventBus.getDefault().post(new DownloadCompleteEvent());
                return;
            }
            //节目有数据
            if (bean != null && bean.getNewProgram() != null && bean.getNewProgram().size() > 0) {
                //删除本地数据库过期的节目数据
                PlayLogic.getInstance().deleteDBProgram(bean);
                for (int i = 0; i < bean.getNewProgram().size(); i++) {
                    //节目信息
                    ProgramBean programBean = bean.getNewProgram().get(i);
                    Map<String, String> sourceInfoMap = (Map<String, String>) programBean.getSourceInfo();
                    if (sourceInfoMap != null) {
                        for (String key : sourceInfoMap.keySet()) {
                            if (key.equals(DeviceUtil.getResolution(getView().getContext()))) {
                                //只获取本设备分辨率的节目素材
                                programBean.setFileInfo(sourceInfoMap.get(key));
                                DaoUtil.insertDB(programBean);//插入数据库
                                //下载节目素材（type: image/video）
                                JSONArray array = new JSONArray(sourceInfoMap.get(key));
                                if (array != null && array.length() > 0) {
                                    List<SourceInfoBean> sourceBeans = new ArrayList<>();
                                    boolean gotoDown = true;
                                    //一个节目素材只会有web 或者图片+视频 三者不会同时存在
                                    for (int m = 0; m < array.length(); m++) {
                                        SourceInfoBean sourceBean = new Gson().fromJson(array.getString(m), SourceInfoBean.class);
                                        if (sourceBean.getFileType().equals("web")) {
                                            gotoDown = false;
                                            break;
                                        }

                                        sourceBean.setProgramVersion(programBean.getProgramVersion());
                                        sourceBeans.add(sourceBean);
                                    }
                                    if (gotoDown) {
                                        //下载节目素材
                                        startDownFile(programBean, sourceBeans);
                                    } else {
                                        //web，下载接口需要调用两次（web直接调用）
                                        //下载完成
                                        uploadProgramDownloadStatus(0, programBean.getProgramVersion(), "");
                                        EventBus.getDefault().post(new DownloadCompleteEvent());
                                    }
                                }
                                break;
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载节目素材
     *
     * @return
     */
    public void startDownFile(ProgramBean programBean, List<SourceInfoBean> sourceList) {
        mList.clear();
        downList.clear();
        currentDownVersion = "";
        if (sourceList != null && sourceList.size() > 0) {
            mList = sourceList;
            for (int i = 0; i < sourceList.size(); i++) {
                downFile(sourceList.get(i));
            }
        }
    }

    /**
     * 下载素材文件
     *
     * @param bean
     */
    private void downFile(SourceInfoBean bean) {
        File file = new File(FileUtils.getProgramFilePath(bean));
        //准备下载
        Message msg = Message.obtain();
        msg.obj = bean;
        msg.what = 2;
        mHandler.sendMessage(msg);

        if (file.exists() && file.isFile() && MD5Util.getFileMD5String(file).equals(bean.getMd5())) {
            //素材已存在，无需要下载
            Message msg1 = Message.obtain();
            msg1.obj = bean;
            msg1.what = 1;
            mHandler.sendMessage(msg1);
            return;
        }

        SingleDownload.getInstance().downSingleFile(bean.getUrl(), FileUtils.getProgramFilePath(bean), new IDownCallbackListener() {
            @Override
            public void completed(String tag) {
                Message msg = Message.obtain();
                msg.obj = bean;
                msg.what = 1;
                mHandler.sendMessage(msg);
            }

            @Override
            public void error(String url, Throwable t) {
                uploadProgramDownloadStatus(2, bean.getProgramVersion(), "" + t.getMessage());
            }

            @Override
            public void progressed() {

            }

            @Override
            public void pending() {
            }
        });
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (DaoUtil.getProgramData() != null && DaoUtil.getProgramData().size() > 0) {
                        List<ProgramBean> programBeanList = new ArrayList<>();
                        for (int i = 0; i < DaoUtil.getProgramData().size(); i++) {
                            ProgramBean programBean = DaoUtil.getProgramData().get(i);
                            String info = programBean.getFileInfo();
                            if (!info.contains("\"fileType\":\"web\"")) {
                                programBeanList.add(programBean);
                            }
                        }
                        int amount = 0;
                        int fileCount = 0;
                        if (programBeanList.size() > 0) {
                            for (int i = 0; i < programBeanList.size(); i++) {
                                ProgramBean mBean = programBeanList.get(i);
                                try {
                                    JSONArray sourceArray = new JSONArray(mBean.getFileInfo());
                                    amount = amount + sourceArray.length();
                                    fileCount = fileCount + PlayLogic.getInstance().getVersionFilesNum(mBean);
                                    if (sourceArray.length() == PlayLogic.getInstance().getVersionFilesNum(mBean)) {
                                        uploadProgramDownloadStatus(0, mBean.getProgramVersion(), "");
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                        if (amount == fileCount) {
                            EventBus.getDefault().post(new DownloadCompleteEvent());
                        }
                    }
                    break;
                case 2:
                    //准备下载
                    SourceInfoBean bean = (SourceInfoBean) msg.obj;
                    String version = bean.getProgramVersion();
                    currentDownVersion = version;
                    if (version.equals(currentDownVersion)) {
                        return;
                    }
                    uploadProgramDownloadStatus(1, version, "");
                    break;
                case 3:
                    //上传离线监播数据完成
                    long mTimestamp = Long.parseLong((String) msg.obj);
                    DaoUtil.deleteByKey(mTimestamp);
                    break;
                case 4:
                    //安装apk
                    UpgradeBean upgradeBean = (UpgradeBean) msg.obj;
                    if (upgradeBean.getIsTiming().intValue() == 1) {
                        //定时升级
                        upgradeAPK(upgradeBean);
                    } else {
                        //马上升级安装apk
                        File apkFile = new File(FileUtils.getAPKFilePath(upgradeBean.getVersionCode().intValue()));
                        DeviceUtil.installApp(apkFile.getAbsolutePath(), getView().getContext());
                    }
                    break;
            }
        }
    };

    private void upgradeAPK(UpgradeBean upgradeBean) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                PlayLogic.getInstance().upgradeAPK(getView().getContext(), upgradeBean);
            }
        }).start();
    }

    /**
     * 获取最新节目信息后，反馈给服务端
     */
    private void getNewestProgramReply(String serialNo, NewestProgramBean bean) {
        if (!NetWorkUtil.isNetworkAvailable(getView().getContext())) {
            return;
        }
        getIPlayModel().getNewestProgramReply(serialNo, new IPlayModel.IProgramReplyCallbackListener() {
            @Override
            public void success() {
                saveProgramData(bean);
            }

            @Override
            public void error(Throwable t) {
                Logger.t(CK.TAG).e("getNewestProgramReply--error:" + t.getMessage());
            }
        });
    }

    /**
     * 获取最新设置信息
     */
    private void getNewestSetting(String serNo) {
        if (!NetWorkUtil.isNetworkAvailable(getView().getContext())) {
            return;
        }
        getIPlayModel().getNewestSetting(new IPlayModel.ISettingCallbackListener() {
            @Override
            public void success(ConfigBean bean) {
                //终端获取设备信息后，调用反馈接口
                getNewestSettingReply(serNo, bean);
            }

            @Override
            public void error(Throwable t) {
                Logger.e(t.getMessage());
            }
        });
    }

    /**
     * 设置本地终端配置
     */
    private void setDeviceLocalConfig(ConfigBean bean) {
        if (bean == null) {
            return;
        }

        /*if (bean.getWifiSwitch().equals(1)) {
            //开启wifi探针，搜集wifi MAC保存
            // startWifiProbe();
        }*/

        /**
         * 设置音量
         */
        if (bean.getDeviceVolume() != null) {
            if (DeviceManager.iBaseMachine == null) {
                DeviceManager.iBaseMachine = App.iBaseMachine;
            }
            int vol = bean.getDeviceVolume().intValue() < 0 ? 0 : bean.getDeviceVolume().intValue();
            ShareUtil.getInstance().put(CK.SP_VOLUME, vol);
            DeviceManager.iBaseMachine.setVolume(vol, AudioManager.STREAM_MUSIC);
        }


        if (Build.MODEL.contains("ZLP86Ni") || Build.MODEL.contains("IoT3288") || Build.MODEL.contains("3280") || Build.MODEL.contains("DS835")) {
            //设置开关机时间
            if (deviceOpenClose.equals("")) {
                deviceOpenClose = (String) SharedPreferencesUtil
                        .getInstance(getView().getContext())
                        .getData(CK.DEVICE_OPEN_CLOSE, "");
            }

            if (!deviceOpenClose.equals(bean.getTimeBoot() + bean.getTimeShutdown())) {
                // return;
                deviceOpenClose = bean.getTimeBoot() + bean.getTimeShutdown();
                PlayLogic.getInstance().setServerOnOffTime(getView().getContext(), bean);
            }

            //重启
            if (bean.getRestartOnce() != null && bean.getRestartOnce().booleanValue()) {
                if (DeviceManager.iBaseMachine == null) {
                    DeviceManager.iBaseMachine = App.iBaseMachine;
                }

                DeviceUtil.getInstance().startUp(getView().getContext(), DeviceManager.iBaseMachine);
            }

            //关机
            if (bean.getShutDownOnce() != null && bean.getShutDownOnce().booleanValue()) {
                if (DeviceManager.iBaseMachine == null) {
                    DeviceManager.iBaseMachine = App.iBaseMachine;
                }

                DeviceUtil.getInstance().shutDown(DeviceManager.iBaseMachine);
            }
        }


        //设置开关屏
        /*if (!TextUtils.isEmpty(bean.getTimeBootScreen()) && !TextUtils.isEmpty(bean.getTimeShutdownScreen())) {
            getView().setScreenOnOff(bean.getTimeBootScreen(), bean.getTimeShutdownScreen());
        }*/


    }

    /**
     * 获取终端最新设置信息后，反馈给服务端
     */
    private void getNewestSettingReply(String serNo, ConfigBean bean) {
        if (!NetWorkUtil.isNetworkAvailable(getView().getContext())) {
            return;
        }
        getIPlayModel().getNewestSettingReply(serNo, new IPlayModel.INewestSettingReplyCallbackListener() {
            @Override
            public void success() {
                if (null != bean) {
                    setDeviceLocalConfig(bean);
                }
            }

            @Override
            public void error(Throwable t) {

            }
        });
    }

    /**
     * 终端设置发生改变，同步服务端
     */
    public void settingSync(int volume) {
        if (!NetWorkUtil.isNetworkAvailable(getView().getContext())) {
            return;
        }
        getIPlayModel().settingSync(volume, new IPlayModel.ISettingSyncCallbackListener() {
            @Override
            public void success() {
                //同步成功
            }

            @Override
            public void error(Throwable t) {
                Logger.e(t.getMessage());
            }
        });
    }

    /**
     * 上传监播报告
     * 每播放完一轮需要请求
     */
    public void reportShow(ProgramInfoBean bean) {
        if (null == bean) {
            return;
        }

        String reportInfo = new Gson().toJson(bean);
        if (!NetWorkUtil.isNetworkAvailable(getView().getContext())) {
            //保存监播数据,待有网络再次上报
            //OffLineData offLineData = new OffLineData();
            //offLineData.setTimestamp(bean.getProgramPlayStartTime());
            // offLineData.setReportInfo(reportInfo);
            // DaoUtil.insertDB(offLineData);
            return;
        }
        Log.v("xika", reportInfo);
        getIPlayModel().reportShow(reportInfo, null, new IPlayModel.IReportShowCallbackListener() {
            @Override
            public void success(String offlineTime) {

            }

            @Override
            public void error(Throwable t) {

            }
        });
    }

    /**
     * 上传监播离线数据
     */
    public void reportOfflineData() {
        //有网络上传离线监播数据
        List<OffLineData> offLineDataList = DaoUtil.getOffLineData();
        if (offLineDataList != null && offLineDataList.size() > 0 && NetWorkUtil.isNetworkAvailable(getView().getContext())) {
            for (int i = 0; i < offLineDataList.size(); i++) {
                OffLineData offLineData = offLineDataList.get(i);
                long timestamp = offLineData.getTimestamp();
                String reportInfo = offLineData.getReportInfo();
                getIPlayModel().reportShow(reportInfo, "" + timestamp, new IPlayModel.IReportShowCallbackListener() {
                    @Override
                    public void success(String offLineTime) {
                        //异步
                        Message msg = Message.obtain();
                        msg.what = 3;
                        msg.obj = offLineTime;
                        mHandler.sendMessage(msg);
                    }

                    @Override
                    public void error(Throwable t) {

                    }
                });
            }
        }

    }

    /**
     * 上传当前节目下载状态
     *
     * @param state   0：已下载;1:下载中;2:下载失败
     * @param version 节目版本号
     * @param reason  失败原因 非空
     */
    public void uploadProgramDownloadStatus(int state, String version, String reason) {
        if (!NetWorkUtil.isNetworkAvailable(getView().getContext())) {
            return;
        }
        getIPlayModel().uploadProgramStatus(state, version, reason, new IPlayModel.IUploadProgramStatusCallbackListener() {
            @Override
            public void success() {
                Log.v("kaka", "节目请求上传完成" + state + ";" + version);
            }

            @Override
            public void error(Throwable t) {
                if (!TextUtils.isEmpty(t.getMessage()) && t.getMessage().contains("Excepition")) {
                    uploadProgramDownloadStatus(0, version, "");
                }
            }
        });
    }

    /**
     * 设备无网络，在线时长超过15分钟，自重启
     * 每天只重启3次
     */
    public void reBootDevice() {
        Flowable.timer(10, TimeUnit.SECONDS, Schedulers.io()).subscribe(new CKSubscriber<Long>(getView().getDisposable()) {
            @Override
            protected void next(Long aLong) {
                String data = ShareUtil.getInstance().getString(CK.REBOOT_TIMES, "");
                if (TextUtils.isEmpty(data)) {
                    //无数据，先保存
                    saveTimes();
                } else {
                    String[] info = data.split(",");
                    int count = Integer.parseInt(info[1]);
                    if (!info[0].equals(key)) {
                        //不是同一天，清楚数据
                        ShareUtil.getInstance().remove(CK.REBOOT_TIMES);
                        saveTimes();
                    } else if (count == 1 || count == 2) {
                        //第二、三次重启间隔1个小时
                        if (!NetWorkUtil.isNetworkAvailable(getView().getContext()) && DeviceUtil.getWorkingHours() >= 1) {
                            //重启
                            if (ShareUtil.getInstance().getLong(CK.NOW_TIME, 0L) == 0) {
                                //未计时无网时间，开始存储计时时间
                                ShareUtil.getInstance().put(CK.NOW_TIME, System.currentTimeMillis());
                            }

                            if ((System.currentTimeMillis() - ShareUtil.getInstance().getLong(CK.NOW_TIME, 0L)) / 1000 / 60 >= 2) {
                                ShareUtil.getInstance().put(CK.REBOOT_TIMES, key + "," + (count + 1));
                                //重置计时
                                ShareUtil.getInstance().put(CK.NOW_TIME, 0L);
                                reboot();
                            }
                        } else if (NetWorkUtil.isNetworkAvailable(getView().getContext()) && DeviceUtil.getWorkingHours() >= 1) {
                            //重置
                            ShareUtil.getInstance().put(CK.NOW_TIME, 0L);
                        }
                    }
                }
            }

            @Override
            protected void finish() {
                String value = ShareUtil.getInstance().getString(CK.REBOOT_TIMES, "");
                if (!TextUtils.isEmpty(value)) {
                    String[] info = value.split(",");
                    if (info[0].equals(key) && Integer.parseInt(info[1]) < 3) {
                        reBootDevice();
                    }
                } else {
                    reBootDevice();
                }
            }
        });
    }

    private void saveTimes() {
        //首次重启15分钟
        if (!NetWorkUtil.isNetworkAvailable(getView().getContext()) && DeviceUtil.getWorkingMinute() >= 15) {
            //重启
            if (ShareUtil.getInstance().getLong(CK.NOW_TIME, 0L) == 0) {
                //未计时无网时间，开始存储计时时间
                ShareUtil.getInstance().put(CK.NOW_TIME, System.currentTimeMillis());
            }

            if ((System.currentTimeMillis() - ShareUtil.getInstance().getLong(CK.NOW_TIME, 0L)) / 1000 / 60 >= 2) {
                ShareUtil.getInstance().put(CK.REBOOT_TIMES, key + "," + 1);
                //重置计时
                ShareUtil.getInstance().put(CK.NOW_TIME, 0L);
                reboot();
            }
        } else if (NetWorkUtil.isNetworkAvailable(getView().getContext()) && DeviceUtil.getWorkingMinute() >= 15) {
            //重置
            ShareUtil.getInstance().put(CK.NOW_TIME, 0L);
        }
    }

    private void reboot() {
        //重启
        if (DeviceManager.iBaseMachine == null) {
            DeviceManager.iBaseMachine = App.iBaseMachine;
        }
        DeviceUtil.getInstance().startUp(getView().getContext(), DeviceManager.iBaseMachine);
    }

    public void isConnectNetwork() {
        Flowable.timer(10, TimeUnit.SECONDS, Schedulers.io()).subscribe(new CKSubscriber<Long>(getView().getDisposable()) {
            @Override
            protected void next(Long aLong) {
                if (NetWorkUtil.isNetworkAvailable(getView().getContext())) {
                    getView().setNetworkFlag(true);
                } else {
                    getView().setNetworkFlag(false);
                }
            }

            @Override
            protected void finish() {
                isConnectNetwork();
            }
        });
    }

    /**
     * 上传终端日志
     */
    /*public void uploadLog() {
        getIPlayModel().uploadLog("run", "http://wwwwww.com", new IPlayModel.IUploadLogCallbackListener() {
            @Override
            public void success() {

            }

            @Override
            public void error(Throwable t) {

            }
        });
    }*/
}
